package prc;

import java.util.ArrayList;

import javax.servlet.http.HttpSession;


public class UserManagement {

	public static ArrayList<User> users = new ArrayList<User>();
	public static ArrayList<User> visibleUsers = new ArrayList<User>();
	public static int totalOnlineUsers=0;
	
	
	
	
	public static void init(){
		User user=new User("admin", "admin", "admin", "admin", 20);
		user.setGroup(User.UserGroup.admin);
		user.setRank(User.UserRank.god);
		addUser(user);
		user=new User("user1", "user1", "user1", "user1", 20);
		addUser(user);
		user=new User("user2", "user2", "user2", "user2", 20);
		addUser(user);
		user=new User("user3", "user3", "user3", "user3", 20);
		addUser(user);
		 
	}
	
	public static User getCurrentUser(HttpSession session){
		String username=(String)session.getAttribute("loggedUser");
		User user=UserManagement.getUserByUsername(username);		
		return user;
	}
	
	public static void logout(HttpSession session){
		int i;
		User user=UserManagement.getCurrentUser(session);
		java.util.Date d=(java.util.Date) session.getAttribute("lastVisitDate");
		if(user!=null&&d!=null)
			user.setLastVisitDate(d);
		
		if(user!=null){
			for(i=0;i<visibleUsers.size();i++)
				if(visibleUsers.get(i).getUsername().equals(user.getUsername())){
					visibleUsers.remove(i);
				}
			if(totalOnlineUsers>0)
				totalOnlineUsers--;
		}
		
		session.setAttribute("loggedUser","");
	}
	
	public static int getVisibleMembers(){
		return visibleUsers.size();
	}
	
	public static int getOnlineUsers(){
		
		return totalOnlineUsers;
	}
	
	public static void login(HttpSession session, String username, boolean hide){
		session.setAttribute( "loggedUser", username);
		session.setAttribute( "lastVisitDate", new java.util.Date());
		User user=getCurrentUser(session);
		if(hide==false){
			visibleUsers.add(user);
		}
		totalOnlineUsers++;
		
	}
	
	public static User getUserByUsername(String username){
		int i;
		for(i=0;i<users.size();i++){
			System.out.println(users.get(i).getUsername());
			if(users.get(i).getUsername().equals(username)){
				return users.get(i);
			}
		}
		return null;
	}
	
	public static void addUser(User u){
		users.add(u);
	}
}
